const redis = require('../../../../redis/init.js')
const constant = require("../../../../constant/index.js");

const userAddLikes = async (req, res) => {
  const { article_id,user_id } = req.body;
  // 文章的点赞集合
  const userLikesSetKey = `${constant.USER_IS_READY_LIKE(user_id, article_id)}`;
  const articleLikesKey = `${constant.ART_LIKE(article_id)}`;
  // 用户点赞文章 ID 集合
  const userLikedArticlesSetKey = `user_id:${user_id}:liked_articles`;
  const hasLiked = await redis.sIsMember(userLikesSetKey, user_id);
  if (hasLiked) {
    res.send({
      code: 400,
      message: "已经点赞",
    });
  } else {
    await redis.hIncrBy(articleLikesKey, "count", 1);
    await redis.sAdd(userLikesSetKey, user_id);
    await redis.sAdd(userLikedArticlesSetKey, article_id + ""); // 将文章 ID 添加到用户点赞文章的集合中
    //将本次set更新后的值给客户端便于实时更新
    const likeCount = await redis.hGet(articleLikesKey,"count")
    await redis.lRange("articlesList", 0, -1).then(async (list) => {
      for (let i = 0; i < list.length; i++) {
        const article = JSON.parse(list[i]);
        if (article.id == article_id) {
          article.like = likeCount;
          await redis.lSet("articlesList", i, JSON.stringify(article));
        }
      }
    });
    //更新文章点赞数
    res.send({
      code: 200,
      message: "点赞成功",
      likeCount
    });
  }
};

module.exports = userAddLikes;
